package cn.netuo.bumbersoll.helper.bluetooth;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.text.TextUtils;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Created by JS_grasp on 2019/3/16.
 */
public class BluetoothHelper {

    private Context mCtx;
    private BluetoothAdapter mBtAdapter = null;
    private BluetoothDevice mBluetoothDevice = null;
    private BluetoothSocket mSocket = null;


    /** 停止搜索 */
    public BluetoothHelper(Context ctx) {
        mCtx = ctx;
        mBtAdapter = BluetoothAdapter.getDefaultAdapter();
    }

    /** 测试蓝牙 */
    public boolean doBtTest(){
        if(mBtAdapter == null) return false;
        return true;
    }

    /** 启动蓝牙 */
    public void doBtEnable(){
        if(mBtAdapter == null) return;
        if(mBtAdapter.isDiscovering()) return;
        if(mBtAdapter.isEnabled()) return;
        mBtAdapter.enable();

        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);    // 开始搜索
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);   // 搜索结束
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);        // 蓝牙状态变化
        filter.addAction(BluetoothDevice.ACTION_FOUND);                 // 搜索到设备

        filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);    // 与远端蓝牙设备配对关系发生变化

        filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);         // 与远端蓝牙设备建立连接
        filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);      // 与远端蓝牙设备断开连接
        mCtx.registerReceiver(mBroadcastReceiver, filter);
    }

    /** 搜索蓝牙 */
    public void doBtDiscovery(){
        if(mBtAdapter == null) return;
        if(!mBtAdapter.isEnabled()) doBtEnable();
        if(mBtAdapter.isDiscovering()) return;
        mBtAdapter.startDiscovery();
    }

    /** 配对连接蓝牙 */
    public void doBtPair(){
        if(mBtAdapter == null)          return;
        if(!mBtAdapter.isEnabled())     return;
        if(mBtAdapter.isDiscovering())  return;
        if(mBluetoothDevice == null)    return;
        try {
            Method createBondMethod = BluetoothDevice.class.getMethod("createBond");
            createBondMethod.invoke(mBluetoothDevice);
        } catch (Exception e) {
            e.getStackTrace();
        }
    }

    /** 通过蓝牙生成socket */
    public void doBtConnectAndSocket(){
        if(mBtAdapter == null) return;
        if(!mBtAdapter.isEnabled()) doBtEnable();
        if(mBtAdapter.isDiscovering()) mBtAdapter.cancelDiscovery();

//        BluetoothDevice device = mBtAdapter.getRemoteDevice(addr);
        BluetoothDevice device = mBluetoothDevice;
        if (device != null) {
            try {
                Method m = BluetoothDevice.class.getMethod("createRfcommSocket", new Class[]{int.class});
                mSocket = (BluetoothSocket) m.invoke(device, Integer.valueOf(1));
                mSocket.connect();
                return;
            } catch (SecurityException | IOException e) {
                System.out.println("-----1:" + e);
            } catch (NoSuchMethodException e) {
                System.out.println("-----2:" + e);
            } catch (IllegalArgumentException e) {
                System.out.println("-----3:" + e);
            } catch (IllegalAccessException e) {
                System.out.println("-----4:" + e);
            } catch (InvocationTargetException e) {
                System.out.println("-----5:" + e);
            }
        }
    }

    /** 通过蓝牙重连socket */
    public void doBtReConnectAndSocket(){
        if(mBtAdapter == null) return;
        if(!mBtAdapter.isEnabled()) doBtEnable();
        if(mBtAdapter.isDiscovering()) mBtAdapter.cancelDiscovery();
        if(mSocket == null) return;
        try {
            mSocket.connect();
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }

    /** 通过蓝牙停止socket */
    public void doBtDisconnect(){
        if(mBtAdapter == null) return;
        if(!mBtAdapter.isEnabled()) doBtEnable();
        if(mBtAdapter.isDiscovering()) mBtAdapter.cancelDiscovery();
        if(mSocket == null) return;
        try {
            mSocket.close();
            mSocket = null;
//            if(outputStream!=null){
//                outputStream.close();
//            }
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }

    /** 删除配对关系(会自动中断数据SOCKET) */
    public void doBtRemovePair(){
        if(mBtAdapter == null) return;
        if(!mBtAdapter.isEnabled()) return;
        if(mBtAdapter.isDiscovering()) return;
        if(mBluetoothDevice == null) return;
        try {
            Method createBondMethod = BluetoothDevice.class.getMethod("removeBond");
            createBondMethod.invoke(mBluetoothDevice);
        } catch (Exception e) {
            e.getStackTrace();
        }
    }

    // 停止搜索
    /** 停止搜索 */
    public void doBtStopDiscovery(){
        if(mBtAdapter == null) return;
        if(!mBtAdapter.isEnabled()) return;
        if(!mBtAdapter.isDiscovering()) return;
        mBtAdapter.cancelDiscovery();
    }

    /** 关掉蓝牙 */
    public void doBtDisable(){
        try{
            mCtx.unregisterReceiver(mBroadcastReceiver);
        }
        catch (Exception e){}
        if(mBtAdapter == null) return;
        if(!mBtAdapter.isEnabled()) return;
        if(mBtAdapter.getState() == BluetoothAdapter.STATE_OFF) return;
        mBtAdapter.disable();
    }

    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            action = TextUtils.isEmpty(action) ? "" : action;
            mBtAdapter.getState();
            switch (action){
                case BluetoothAdapter.ACTION_DISCOVERY_STARTED:{                // 开始搜索
                    System.out.println("开始搜索");
                    break;
                }
                case BluetoothAdapter.ACTION_DISCOVERY_FINISHED:{               // 搜索结束
                    System.out.println("搜索结束");
                    break;
                }
                case BluetoothAdapter.ACTION_STATE_CHANGED:{                    // 蓝牙状态变化
                    System.out.println("蓝牙设备状态变化");
                    break;
                }
                case BluetoothDevice.ACTION_FOUND:{                     // 搜索到设备
                    BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    String name     = device.getName();
                    String addr     = device.getAddress();
                    int bondStatus  = device.getBondState();
                    int type        = device.getType();

                    System.out.println("发现新蓝牙设备");
                    System.out.println("name:"          + name);
                    System.out.println("addr:"          + addr);
                    System.out.println("bondStatus:"    + bondStatus);
                    System.out.println("type:"          + type);

                    if("测试手机".equals(name)){
                        mBluetoothDevice = device;
                    }
                    break;
                }
                case BluetoothDevice.ACTION_BOND_STATE_CHANGED:{        // 与远端蓝牙设备配对关系发生变化
                    System.out.println("与远端蓝牙设备配对关系发生变化");
                    break;
                }
                case BluetoothDevice.ACTION_ACL_CONNECTED:{             // 连接成功
                    System.out.println("连接成功");
                    break;
                }
                case BluetoothDevice.ACTION_ACL_DISCONNECTED:{          // 断开连接
                    System.out.println("断开连接");
                    break;
                }
            }
        }
    };
}
